#pragma once

#include <string>
#include <string_view>
#include <vector>

namespace solution_071
{

class Solution
{
public:
    std::string simplifyPath(std::string path)
    {
        if (path.back() != '/')
            path.push_back('/');
        std::vector<std::string_view> nodes;
        int i = 0;
        int j = 1;
        while (j < (int)path.size()) {
            int len = j - i - 1;
            if (path.at(j) == '/') {
                if (len == 2 && path.at(i + 1) == '.' && path.at(i + 2) == '.') {
                    if (!nodes.empty())
                        nodes.pop_back();
                } else if (len > 0 && !(len == 1 && path.at(i + 1) == '.')) {
                    nodes.emplace_back(path.data() + i + 1, len);
                }
                i = j;
            }
            ++j;
        }

        std::string simple_path;
        for (auto& node : nodes) {
            simple_path += "/";
            simple_path += node;
        }
        if (simple_path.empty())
            simple_path.push_back('/');
        return simple_path;
    }
};

}  /* namespace solution_071 */
